<template>
	<view class="chat-message-wrap">
		<view class="flex-row">
			<view id="chat-message-text" v-html="messageText" class="chat-message-text" :class="{reverse: isReverse && isSenderThemselve}" @tap="onClick"></view>
		
			<template v-if="isTranslate && !translate">
				<image v-if="!isSenderThemselve && !translating" @tap="onTranslate" class="translate" src="@/static/img/svg/translate.svg"></image>
				<xbc-loading v-if="translating"></xbc-loading>
			</template>
		</view>
		<view v-if="!isSenderThemselve && translate" class="translate-result">{{ translate }}</view>
	</view>
</template>

<script lang="ts" setup>
import { cloneDeep } from 'lodash'
import { computed, reactive, ref } from 'vue'
import { messageProps, useMessage } from '@/hooks/useMessage'
import IM from '@/common/xbcim'

const translate = ref('')
const translating = ref(false)
const isTranslate = ref(false)
const props = defineProps(messageProps)
const { isSenderThemselve, messageContent } = useMessage(props)
const messageText = computed(() => {
	// 自动翻译
	if(props.message.translate){
		translate.value = JSON.parse(props.message.translate)?.data
	}
	return messageContent.value?.data || ''
	
	// 匹配超链接
	// const regex = /(https?:\/\/[\w\-._~:/?#\[\]@!$&'()*+,;=%]+)/g
	// const message = messageContent.value?.data || ''
	// return message ? message.replace(regex, '<a class="chat-message-text-link" href="$1" target="_blank">$1</a>') : ''
})

// 翻译
function onTranslate() {
	translating.value = true
	IM.translateMessage(props.message).then((res : any) => {
		translating.value = false
		translate.value = JSON.parse(res?.translate || '{}')?.data
	}).catch(() => {
		translating.value = false
	})
}

// 右键菜单
const commands = reactive([
	{ name: '复制', command: 'copy' },
	{ name: '引用', command: 'quote' },
	{ name: '撤回', command: 'revoke' },
	{ name: '删除', command: 'deleteMessage' }
])

// 点击链接
function onClick(event) {
	const target = event.target
	if (target.tagName === 'A') {
		// todo
	}
}
</script>

<style lang="scss">
.chat-message-text-link {
	color: #6565f7;
	text-decoration: none;

	&:hover {
		text-decoration: underline;
	}
}
</style>
<style lang="scss" scoped>
.chat-message-wrap{
	flex: 1;
	
	> .flex-row{
		justify-content: flex-start;
	}
}

.translate {
	opacity: 0.6;
	margin-left: 16rpx;
	align-self: flex-end;
	@include fullsize(36rpx);
}

.translate-result{
	color: #333;
	display: inline-block;
	padding: 20rpx;
	font-size: 30rpx;
	margin-top: 10rpx;
	border-radius: 10rpx;
	background-color: #fff;
}

.chat-message-text {
	color: #333;
	font-size: 28rpx;
	width: fit-content;
	user-select: text;
	padding: 20rpx 24rpx;
	word-break: break-all;
	transition: all 0.1s ease;
	border-radius: 0 10rpx 10rpx 10rpx;
	background-color: rgba(0, 0, 0, 0.05);

	&:hover {
		background-color: rgba(0, 0, 0, 0.08);
	}

	&.reverse {
		background-color: rgba(131, 216, 88, 0.8);
		border-radius: 10rpx 0 10rpx 10rpx;

		&:hover {
			background-color: rgba(131, 216, 88, 0.9);
		}
	}
}
</style>